package com.yegs.jltqc.U8ServiceImpl;

import com.yegs.jltqc.TO.NamePageQuery;
import com.yegs.jltqc.TO.PpbarcodePageQuery;
import com.yegs.jltqc.U8Service.PpbarcodeService;
import com.yegs.jltqc.U8Service.U8VendorService;
import com.yegs.jltqc.common.StoreException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PpBarcodeServiceImpl implements PpbarcodeService {

    @Autowired
    @Qualifier("u8JdbcTemplate")
    private JdbcTemplate u8JdbcTemplate;


    Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public Page<Map<String, Object>> query(PpbarcodePageQuery query) {
        String sql = "SELECT TOP " + (query.getPageIndex()) * query.getPageSize()+
                " ROW_NUMBER() OVER(ORDER BY id ASC) AS ROWID,* from qc_outcome where 1=1 ";
        if(query.getDdate() != null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sql += " and ddate = '"+sdf.format(query.getSddate())+"'";
        }
        sql = "select * from ("+sql +") as temp1 where ROWID > " + (query.getPageIndex()-1) * query.getPageSize();
        List<Map<String, Object>> list = u8JdbcTemplate.queryForList(sql);
        sql = "select count (*) from qc_outcome where 1=1 ";
        if(query.getDdate() != null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sql += " and ddate = '"+sdf.format(query.getSddate())+"'";
        }
        int total = u8JdbcTemplate.queryForObject(sql,Integer.class);
        PageRequest request = PageRequest.of(query.getPageIndex() -1,query.getPageSize());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        list.forEach(map -> { map.put("dDate",sdf.format((Date) map.get("dDate"))); });
        PageImpl page = new PageImpl(list,request,total);
        return page;
    }

    @Override
    public Map<String, Object> findByBarcode(String barcode) {
        String sql = "select * from JLTSystem.dbo.ymh_PPBarcode where cbarcode = ? ";
        List<Map<String, Object>> list = u8JdbcTemplate.queryForList(sql, barcode);
        if(list.size() == 0){
            return null;
        }
        return list.get(0);
    }

    @Override
    public void updateByAutoid(Long autoid, Long qty) {
        String faile = "update  ymh_PPBarcode set notqualifiedqty= qty where cbarcode <='B202111110033' and modid = 1000620326";
        u8JdbcTemplate.update("update JLTSystem.dbo.ymh_Barcode set qualifiedqty += ? where MoDId = ? ", qty, autoid);
    }
    @Override
    public void success(String barcode, Long modid) {
        String success = "update  JLTSystem.dbo.ymh_Barcode set qualifiedqty= qty where cbarcode <= ? and modid = ? and (qualifiedqty != qty or notqualifiedqty != qty )";
        u8JdbcTemplate.update(success, barcode, modid);
    }

    @Override
    public void success(Long modid) {
        String success = "update  JLTSystem.dbo.ymh_Barcode set qualifiedqty= qty where modid = ? ";
        u8JdbcTemplate.update(success, modid);
    }

    @Override
    public void fail(String barcode, Long modid) {
        String faile = "update  JLTSystem.dbo.ymh_Barcode set notqualifiedqty= qty where cbarcode <=? and modid = ? and (qualifiedqty != qty or notqualifiedqty != qty )";
        u8JdbcTemplate.update(faile, barcode, modid);
    }

    @Override
    public void fail(Long modid) {
        String faile = "update  JLTSystem.dbo.ymh_Barcode set notqualifiedqty= qty where modid = ? ";
        u8JdbcTemplate.update(faile, modid);
    }
    @Override
    public void updateByBarcode(String cbarcode,int status,int all){
        u8JdbcTemplate.execute("{call JLTSystem.dbo.ymh_updateBarcodestatus('" + cbarcode + "'," + status+ ", " + all + ")}");
        u8JdbcTemplate.execute("{call JLTSystem.dbo.ymh_syncrdpprecord10_forqc('"+cbarcode+"')}");
    }

    @Override
    public void updateByBarcodestatus(String cbarcode, int status, int all, int startindex, int endindex) {
            u8JdbcTemplate.execute("{call JLTSystem.dbo.ymh_updateBarcodestatus('" + cbarcode + "'," + status+ ", " + all + ", " + startindex + ", " + endindex + ")}");
        u8JdbcTemplate.execute("{call JLTSystem.dbo.ymh_syncrdpprecord10_forqc('"+cbarcode+"')}");
    }

    @Override
    public boolean checkByMoidAndScbarcodenoAndEcbarcodeno(Long modid, int startindex, int endindex) {
        //TODO 确认cbarcodeno的范围
        String sql = "select * from ymh_PPBarcode where modid = ? and cbarcodeno >= ? and cbarcodeno <= ? and stepvalue = '质检' ";
        List<Map<String, Object>> list = u8JdbcTemplate.queryForList(sql, modid, startindex, endindex);
        return list.size() == 0;
    }

    @Override
    public List<Map<String, Object>> findAllByModid(Long modid) {
        String sql = "select * from JLTSystem.dbo.ymh_PPBarcode where modid = ? and kbtype <> '老化' order by cbarcodeno ";
        return u8JdbcTemplate.queryForList(sql,modid);
    }

    @Override
    public  List<Map<String, Object>> findByMoidAndScbarcodenoAndEcbarcodeno(Long modid, int startindex, int endindex) {
        String sql = "select * from JLTSystem.dbo.ymh_PPBarcode where modid = ? and cbarcodeno >= ? and cbarcodeno <= ? and stepvalue = '质检' ";
        return u8JdbcTemplate.queryForList(sql, modid, startindex, endindex);
    }

    @Override
    public Integer insertymhWorkshopPprd10(String ccode, Date ddate, String cwhcode, String cmarker) {
        String sql = "insert into JLTSystem.dbo.ymh_workshop_pprd10(ccode,ddate,cwhcode,cmaker) values (?,?,?,?)";
        u8JdbcTemplate.update(sql, ccode, ddate, cwhcode, cmarker);
        List<Map<String, Object>> list  = u8JdbcTemplate.queryForList("select top 1 * from JLTSystem.dbo.ymh_workshop_pprd10 " +
                "where ccode = ? and cwhcode = ? and cmaker = ? order by id desc ",ccode,cwhcode,cmarker);

        if(list.size() ==0 ){
            return  null;
        }else{
            return (Integer)list.get(0).get("id");
        }
    }



    @Override
    public void insertymhWorkshopPprds10(Integer pid, String cinvcode,Double qty, String cposcode, String cbarcode, Long result,String ccode,Date ddate,String cwhcode, String cmaker) {
        Map<String, Object> map = this.selectymhWorkshopPprds10ByCbarcode(cbarcode);
        if(map != null){
            return;
        }
        String sql = "insert into JLTSystem.dbo.ymh_workshop_pprds10(pid,cinvcode,qty,cposcode,cbarcode,result,ccode,ddate,cwhcode,cmaker) values (?,?,?,?,?, ?,?,?,?,?)";
        String d = null;
        if(ddate != null){
            d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(ddate);
        }
        u8JdbcTemplate.update(sql,pid,cinvcode,qty,cposcode,cbarcode,result,ccode, d, cwhcode, cmaker);
    }

    @Override
    public Map<String, Object> selectymhWorkshopPprds10ByCbarcode(String cbarcode) {
        String sql = "select top 1 * from JLTSystem.dbo.ymh_workshop_pprds10 where cbarcode = ? ";
        List<Map<String, Object>> list = u8JdbcTemplate.queryForList(sql, cbarcode);
        if(list.size() ==0 ){
            return  null;
        }else{
            return list.get(0);
        }
    }

    @Override
    public void insertQcrecode(String cbarcode, Long modid, Date ddate, String result) {
        String sql = "insert into JLTSystem.dbo.qcrecord(cbarcode,modid,ddate,result) values (?,?,?,?)";
        String d = null;
        if(ddate != null){
            d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(ddate);
        }
        u8JdbcTemplate.update(sql,cbarcode,modid,d,result);
    }

    @Override
    public void updateYmhPoqcdata(String isqc, String cbarcode) {
        logger.info(isqc+":"+cbarcode);
        String sql = "update JLTSystem.dbo.ymh_poqcdata set isqc = ? where cbarcode = ? ";
        u8JdbcTemplate.update(sql,isqc,cbarcode);
    }

    @Override
    public Integer findymhWorkshopPprds10(String cbarcode) {
        Map<String, Object> map = u8JdbcTemplate.queryForMap("select top 1 * from  JLTSystem.dbo.ymh_workshop_pprds10 where cbarcode = ?", cbarcode);
        if(map == null){
            return null;
        }
        return (Integer) map.get("id");
    }


    @Override
    public String getCCode() {
        Map<String, Object> stringObjectMap = u8JdbcTemplate.queryForMap("{call JLTSystem.dbo.a_pr_GenCode('CP')}");
        return (String) stringObjectMap.get(stringObjectMap.keySet().iterator().next());
    }

    @Override
    public void updateppbarcode(String cbarcode, String remark, Date date) {
        String d = "";
        if(date != null){
            d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
            u8JdbcTemplate.execute("{call JLTSystem.dbo.ymh_updateppbarcode('" + cbarcode + "','" + remark+ "','" + d+ "')}");
        }else{
            u8JdbcTemplate.execute("{call JLTSystem.dbo.ymh_updateppbarcode('" + cbarcode + "','" + remark+ "',null)}");
        }

    }

    @Override
    public void syncrdpprecord10_forqc2(Integer id) {
        u8JdbcTemplate.execute("{call JLTSystem.dbo.ymh_syncrdpprecord10_forqc2(" + id + ")}");
    }


}
